package controller;

import beans.HttpConfig;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

public class SocketLogFileDownload extends HttpServlet {
    private static final long serialVersionUID = -7687152651151291346L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/x-msdownload");
        String filePath = request.getParameter("uri");
        filePath = HttpConfig.socketLogFileUri+filePath;
        File file = new File(filePath);
        //解决乱码问题
        String filename = URLEncoder.encode(file.getName(), "utf-8");
        //重置输出流
        response.reset();
        response.addHeader("Content-Disposition", "attachment;filename=" + filename);//设置文件名
        response.setContentType("application/octet-stream");//设置文件类型
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());//获取二进制输出流
        //读取文件数据
        InputStream fis = new BufferedInputStream(new FileInputStream(filePath));
        byte[] buffer = new byte[4048];

        int size = 0;
        int len = 0;
        byte[] buf = new byte[1024];
        while ((size = fis.read(buf)) != -1) {
            len += size;
            toClient.write(buf, 0, size);
            // 打印下载百分比
//             System.out.println("下载了-------> " + len * 100 / fileLength + "%\n");
        }

        //    fis.read(buffer);
        fis.close();
        //输出文件数据
        toClient.flush();
        //     toClient.write(buffer);
        toClient.close();

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}